import { dataSource } from "../../db/typeorm";
import { Role } from "../../entity/role";
import { formatPage, formatPageFileterData } from "../../utils/pages";

// 查询用户分页列表
export async function rolePage(
  query: { [key: string]: any } & { pageIndex: number; pageSize: number },
) {
  const { pageIndex, pageSize } = formatPage(query);
  const queryData = formatPageFileterData(query);
  let querySql = dataSource.getRepository(Role).createQueryBuilder("role");
  for (const key in queryData) {
    if (Object.prototype.hasOwnProperty.call(queryData, key)) {
      if (["role_name"].includes(key)) {
        querySql = querySql.andWhere(`${key} LIKE :${key}`, {
          [`${key}`]: `%${queryData[key]}%`,
        });
      } else {
        querySql = querySql.andWhere(`${key} = :${key}`, {
          [`${key}`]: queryData[key],
        });
      }
    }
  }
  querySql = querySql
    .orderBy("create_time", "DESC")
    .take(pageSize)
    .skip((pageIndex - 1) * pageSize)
    .select(["role.role_id", "role.role_name", "role.create_time"]);

  const records = await querySql.getMany(); // 获取查询结果
  const total = await querySql.getCount(); // 获取符合条件的数据总数

  return { total, records };
}

// 添加角色
export async function roleAdd(data: Role) {
  const response = await dataSource
    .createQueryBuilder()
    .insert()
    .into(Role)
    .values(data)
    .execute();
  return response;
}

// 查询角色
export async function roleFindOneByRoleId(role_id: string | number) {
  return await dataSource
    .getRepository(Role)
    .findOneBy({ role_id: Number(role_id) });
}

// 更新角色信息
export async function roleUpdate(data: Role) {
  const result = await dataSource
    .createQueryBuilder()
    .insert()
    .update(Role)
    .set(data)
    .where("role_id = :id", { id: data.role_id })
    .execute();
  return result;
}

// 根据ids 删除角色
export async function roleDelByRoleIds(ids: string[]) {
  await dataSource.getRepository(Role).delete(ids);
}
